<template>
  <div class="case-chart">
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script setup lang="ts">
//单独展示case结果的，不和barchart混在一起
import { ref, onMounted, watch, onUnmounted } from "vue";
import { useImageStore } from "@/stores/imageStore";
import { ECharts, EChartsOption } from "echarts";
import { DiseaseCase } from "@/types/imageAndFile";
const store = useImageStore();
import * as echarts from "echarts";

const chartRef = ref<HTMLDivElement | null>(null);
let chartInstance: ECharts | null = null;

/**
 * 计算病例占比
 * @param cases 列表
 * @param total 病例总数
 */
const calculateProportions = (
  cases: DiseaseCase[],
  total: number
): string[] => {
  //总数为0返回全0数组
  if (total <= 0) return cases.map(() => "0.00");
  //计算比例
  return cases.map((c) => {
    const safeCount =
      typeof c.count === "number" && !isNaN(c.count) ? c.count : 0;
    return (safeCount / total).toFixed(2);
  });
};

onMounted(() => {
  //DOM存在
  if (!chartRef.value) return;
  chartInstance = echarts.init(chartRef.value);

  const totalDiseases: number = store.cases.reduce((sum, c) => {
    const safeCount =
      typeof c.count === "number" && !isNaN(c.count) ? c.count : 0;
    return sum + safeCount;
  }, 0);

  const option: EChartsOption = {
    title: {
      text: "病例比例数目",
    },
    tooltip: {
      trigger: "axis",
      formatter: function (params: any) {
        const param = params[0];
        const percentage = (Number(param.value) * 100).toFixed(2);
        return `${param.name}: ${param.value} (${percentage}%)`;
      },
    },
    xAxis: {
      type: "category",
      data: store.cases.map((c: DiseaseCase) => c.disease),
    },
    yAxis: {
      type: "value",
      max: 1,
      min: 0,
      axisLabel: {
        formatter: (value: number) => `${(value * 100).toFixed(0)}%`,
      },
    },
    series: [
      {
        name: "病例占比",
        data: calculateProportions(store.cases as DiseaseCase[], totalDiseases),
        type: "bar"
      },
    ],
  };
  chartInstance.setOption(option);
  watch(
    () => store.cases,
    (newCases: DiseaseCase[]) => {
      if (!chartInstance) return;
      const totalDiseases: number = newCases.reduce((sum, c) => {
        const safeCount =
          typeof c.count === "number" && !isNaN(c.count) ? c.count : 0;
        return sum + safeCount;
      }, 0);

      chartInstance.setOption({
        xAxis: {
          data: newCases.map((c) => c.disease),
        },
        series: [
          {
            data: calculateProportions(newCases, totalDiseases),
          },
        ],
      });
    },
    { deep: true }
  );
});

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener("resize", () => {
    chartInstance?.resize();
  });
});
</script>

<style scoped>
.case-chart {
  padding: 20px;
}

.chart {
  width: 100%;
  height: 400px;
}
</style>
